package com.mediacloud.app.newsmodule.fragment

import android.text.TextUtils
import android.util.Log
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONException
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.eventTrack.TXReportManager
import com.google.gson.Gson
import com.luck.picture.lib.tools.DoubleUtils
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.MagazineListAdapter
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.utils.NetWorkUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.mmkv.MMKV
import com.utils.ClickUtils.delayClickable
import com.utils.ExposurePoolService
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_service_navigation.*
import kotlinx.android.synthetic.main.fragment_service_navigation.recyclerView
import kotlinx.android.synthetic.main.fragment_video_seamless_layout.*
import kotlin.math.abs

class MagazineFragment : HqyNavFragment(), ToolBarActionF5OrTop,
        OnRefreshLoadMoreListener {

    var catalogID: String? = null
    var catalogItem: CatalogItem? = null
    var preLoadKit: ListPreLoadKit<MutableList<ArticleItem>>? = null
    protected var pageSize = 20
    var adapter: BaseMultiItemQuickAdapter<ArticleItem, BaseViewHolder>? = null

    var firstOpen = true
    override fun getLayoutResID(): Int {
        return R.layout.fragment_magazine_layout
    }

    override fun initArgs() {
        super.initArgs()
        navPaddingTopMatch()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
    }

    override fun initToRefresh() {
        useCache()
    }
    private fun useCache() {
        val refreshData = MMKV.mmkvWithID(XKey.MAGAZINE_REFRESH_DATA).getString(catalogID, null)
        if (!TextUtils.isEmpty(refreshData)) {
            try {
                //TODO
                val articleItem = JSON.parseArray(refreshData, ArticleItem::class.java)
                preLoadKit!!.hasMore = true
                preLoadKit!!.preLoadData.add(articleItem)
                showStateView(TYPE_LOADING, false)
                setData(articleItem)
                preLoadKit!!.preload()
            } catch (e: JSONException) {
                e.printStackTrace()
                innerUserCache()
            }
        } else {
            innerUserCache()
        }
    }

    private fun innerUserCache() {
        val refreshData = MMKV.mmkvWithID(XKey.MAGAZINE_REFRESH_DATA).getString(catalogID, null)
        if (adapter != null && !TextUtils.isEmpty(refreshData)) {
            val articleItem = JSON.parseArray(refreshData, ArticleItem::class.java)
            showStateView(TYPE_LOADING, false)
            setData(articleItem)
        } else {
            showStateView(TYPE_LOADING, false)
            preLoadKit?.onRefresh()
            getData()
        }
    }
    override fun initView() {
        loadingView = findViewById(R.id.mLoadingView)
        loadingView.setOnClickListener { v ->
            delayClickable(v)
            if (currentState !== TYPE_LOADING) {
                showStateView(TYPE_LOADING, false)
                getData()
            }
        }
        initStateView()
        showStateView(TYPE_LOADING, false)
        adapter = MagazineListAdapter(null)
        val manager = GridLayoutManager(requireContext(), 3)
        recyclerView.layoutManager = manager
        recyclerView.adapter = adapter
        adapter?.bindToRecyclerView(recyclerView)
        adapter?.setEmptyView(R.layout.empty_ws24, recyclerView)
        adapter?.setOnItemChildClickListener { adapter, view, position ->
            if (DoubleUtils.isFastDoubleClick()) {
                return@setOnItemChildClickListener
            }
            val item = adapter.getItem(position)
            if (item is ArticleItem) {
                NewsItemClickUtils.OpenItemNewsHandle(requireContext(), item.type, item, CatalogItem())
                TXReportManager.getInstance().app_jhapp_magazine_interact(item, "点击查看")
            }

        }
        preLoadKit = object :
                ListPreLoadKit<MutableList<ArticleItem>>(requireContext(), smartRefreshLayout!!) {
            override fun onSetData(data: MutableList<ArticleItem>) {
                setData(data)
            }

            override fun onPreload(preNum: Int) {
                preload(preNum)
            }


        }
        smartRefreshLayout.setOnRefreshLoadMoreListener(this)

        getData()


        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        app_jhapp_magazine_imp()
                    }

                }
            }

        })
    }

    private fun setData(t: MutableList<ArticleItem>) {
        if (preLoadKit?.pageNum == 1) {
            smartRefreshLayout.setEnableLoadMore(true)
            adapter?.setNewData(t)
            if (preLoadKit?.pageNum == 1 && t.size > 0) {
                recyclerView.scrollToPosition(0)
            }
            if(NetWorkUtil.IsNetWorkEnable(context)){
                MMKV.mmkvWithID(XKey.MAGAZINE_REFRESH_DATA).remove(catalogID)
                val toJson = Gson().toJson(t)
                MMKV.mmkvWithID(XKey.MAGAZINE_REFRESH_DATA).putString(catalogID, toJson)
            }
        } else {
            adapter?.addData(t)
        }
        smartRefreshLayout.finishRefresh()
        smartRefreshLayout.finishLoadMore()
        if (adapter!!.data.size == 0) {
            showStateView(TYPE_NO_CONTENT, false)
        } else {
            closeStateView()
        }
    }

    fun getData() {
        val map: MutableMap<String, String> = HashMap()
        map["only_article"] = "1"
        map["no_content"] = "1"
        map["client"] = DataInvokeUtil.ClientFlag
        map["page"] = "" + preLoadKit?.pageNum
        map["perPage"] = "" + pageSize
        val d = DataInvokeUtil.ziMeiTiApi
                .getContentList("$catalogID", map)
                .subscribeOn(Schedulers.io())
                .map {
                    val temp = ArticleListData()
                    temp.readFromJson(it.body())
                    preLoadKit?.hasMore = temp.more
                    buildGroup(temp.articleList)
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<MutableList<ArticleItem>> {
                    override fun onSubscribe(d: Disposable) {

                    }

                    override fun onNext(t: MutableList<ArticleItem>) {
                        if (isDispose) return
                        dataReady = true
                        preLoadKit?.preLoadData?.add(t)
                        setData(t)
                        preLoadKit?.preload()
                        if (hadChoosed||firstOpen) {
                            firstOpen = false
                            app_jhapp_magazine_imp()
                        }
                    }

                    override fun onError(e: Throwable) {
                        smartRefreshLayout?.finishRefresh()
                        if (adapter!!.data.size == 0) {
                            showStateView(TYPE_NO_CONTENT, false)
                        } else {
                            closeStateView()
                        }
                    }

                    override fun onComplete() {

                    }
                })
    }

    private fun preload(preNum: Int) {
        val map: MutableMap<String, String> = HashMap()
        map["only_article"] = "1"
        map["no_content"] = "1"
        map["client"] = DataInvokeUtil.ClientFlag
        map["page"] = "$preNum"
        map["perPage"] = "" + pageSize
        val d = DataInvokeUtil.ziMeiTiApi
                .getContentList("$catalogID", map)
                .map {
                    val temp = ArticleListData()
                    temp.readFromJson(it.body())
                    preLoadKit?.hasMore = temp.more
                    buildGroup(temp.articleList)
                }.subscribeOn(Schedulers.io())
                .onErrorReturn { null }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<MutableList<ArticleItem>> {
                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: MutableList<ArticleItem>) {
                        preLoadKit?.onPreloadSuccess(t, preNum)
                    }

                    override fun onError(e: Throwable) {
                        preLoadKit?.onPreloadFail(preNum)
                    }

                    override fun onComplete() {

                    }
                })
    }

    private fun buildGroup(list: MutableList<ArticleItem>): MutableList<ArticleItem> {
        val finalData: MutableList<ArticleItem> = ArrayList()
        list.forEach {
            try {
                finalData.add(it)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return finalData
    }

    override fun f5() {
        recyclerView.scrollToPosition(0)
        smartRefreshLayout.setEnableRefresh(true)
        smartRefreshLayout.autoRefresh(200)
    }

    override fun gun() {

    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        preLoadKit?.onRefresh()
        getData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        preLoadKit!!.onLoadMore()
    }

    private var dataReady = false
    private val app_jhapp_video_impRunable: Runnable = Runnable {
        ExposurePoolService.getExecutorService().execute {
            try {

                TXReportManager.getExposureArticles(recyclerView, adapter?.data as MutableList<ArticleItem>?)?.forEach { obj ->
                    TXReportManager.getInstance().app_jhapp_magazine_imp(obj)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun app_jhapp_magazine_imp() {
        if (!dataReady) return
        recyclerView?.apply {
            removeCallbacks(app_jhapp_video_impRunable)
            postDelayed(app_jhapp_video_impRunable, TXReportManager.EXPOSURE_DELAY)
        }
    }
}